package com.cade.agriculturemall.view.home.search;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseActivity;
import com.cade.agriculturemall.db.RecordSQLiteOpenHelper;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.SearchRecord;
import com.cade.agriculturemall.widget.EmptyLayout;
import com.cade.agriculturemall.widget.HorizontalFlowLayoutManager;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity<SearchContract.IPresenter> implements SearchContract.IView {
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private RecyclerView recyclerViewLabel;
    private RecyclerView recyclerViewSeeks;
    private SearchAdapter searchAdapter;
    private SeekAdapter seekAdapter;
    private EmptyLayout mEmptyLayout;

    private boolean isCreateDb = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
    }

    @Override
    public void setupView() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getLocal();
    }

    /**
     * 获取本地数据
     */
    private void getLocal() {
        //创建数据库（表）
        //调用mDbManager.getDBHelper()
        helper = new RecordSQLiteOpenHelper(this);
        isCreateDb = true;
        Cursor cursor = helper.getReadableDatabase().rawQuery("select * from " + RecordSQLiteOpenHelper.T_NAME, null);
        // 创建adapter适配器对象
        StringBuffer sb = new StringBuffer();
        List<SearchRecord> list = new ArrayList<>();
        if (cursor.getCount() != 0) {
            while (cursor.moveToNext()) {
                sb.append("_id=").append(cursor.getString(cursor.getColumnIndex(RecordSQLiteOpenHelper.TABLE_ID))).append(" ")
                        .append("name=").append(cursor.getString(cursor.getColumnIndex(RecordSQLiteOpenHelper.TABLE_NAME))).append(" ")
                        .append("\n");
                SearchRecord searchRecord = new SearchRecord();
                searchRecord.setKet(cursor.getString(cursor.getColumnIndex(RecordSQLiteOpenHelper.TABLE_ID)));
                searchRecord.setVaule(cursor.getString(cursor.getColumnIndex(RecordSQLiteOpenHelper.TABLE_NAME)));
                list.add(searchRecord);
            }
        }
        cursor.close();
        searchAdapter = new SearchAdapter(this, list, null);
        recyclerViewLabel.setAdapter(searchAdapter);
        mEmptyLayout.setVisibility(View.GONE);
    }

    @Override
    public void setupEvent() {
        final EditText edtSearch = (EditText) findViewById(R.id.search_et_search);
        edtSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        edtSearch.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        edtSearch.setSingleLine(true);
        TextView tvCancel = (TextView) findViewById(R.id.search_tv_cancel);
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (keyEvent.getAction()) {
                        case KeyEvent.ACTION_UP:
                            String keyWord = edtSearch.getText().toString().trim();
                            if (!TextUtils.isEmpty(keyWord)) {
                                insertData(keyWord);
//                            goNext();
                                mPresenter.query(keyWord);
                                edtSearch.setText("");
                            }
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        recyclerViewLabel = (RecyclerView) findViewById(R.id.search_recyclerview_label);
        recyclerViewSeeks = (RecyclerView) findViewById(R.id.search_recyclerview_seeks);
        mEmptyLayout = (EmptyLayout) findViewById(R.id.search_empty_layout);
        HorizontalFlowLayoutManager layoutManager = new HorizontalFlowLayoutManager();
        layoutManager.setAutoMeasureEnabled(true);
        recyclerViewSeeks.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewLabel.setLayoutManager(layoutManager);

    }

    public void itemSearch(String keyWord) {
        mPresenter.query(keyWord);
    }

    @Override
    public void setupData() {
    }

    @Override
    public SearchContract.IPresenter setupPresenter() {
        return new SearchPresenter(this);
    }

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        String sql = "insert into " + helper.T_NAME + " values( null ,'" + tempName + "')";
        db.execSQL(sql);
    }

    /**
     * 清空数据
     */
    public void deleteData() {
        db = helper.getWritableDatabase();
        String sql = "DELETE FROM " + helper.T_NAME;
        db.execSQL(sql);
        searchAdapter.notifyDataSetChanged();
    }

    @Override
    public void getData(List<GoodsDetailEntity> list) {
        mEmptyLayout.reset();
        mEmptyLayout.setVisibility(View.VISIBLE);
        recyclerViewLabel.setVisibility(View.GONE);
        if (list.size() == 0) {
            mEmptyLayout.empty();
        } else {
            seekAdapter = new SeekAdapter(this, list);
            recyclerViewSeeks.setAdapter(seekAdapter);
        }
    }
}
